"""
在线词典:客户端,
"""
from socket import socket
import sys
import re


ADDR = (("176.4.18.30",8864))

class Handle:
    @staticmethod
    def check(info):
        if re.findall("^\w{4,12}$",info):
            return True


    def __init__(self):
        self.sock = self._get_sock()

    def _get_sock(self):
        tcp_sock = socket()
        tcp_sock.connect(ADDR)
        return tcp_sock

    def register(self,name,password):
        if Handle.check(name) and Handle.check(password):
            data = "R %s %s" % (name, password)   #这步的格式得记得
            self.sock.send(data.encode())
            data = self.sock.recv(1024)
            if data == b"T":
                print("注册成功")
                return True
            elif data == b"F":
                print("注册失败,请重新注册")
            else:
                print("404")
        else:
            print("用户名和密码必须为4-12位数字,字母,下划线")

    def login(self,name,password):
        data = "L %s %s" % (name, password)  # 这步的格式得记得
        self.sock.send(data.encode())
        data = self.sock.recv(1024)
        if data == b"T":
            print("登录成功")
            return True
        elif data == b"F":
            print("登录失败,请重新登录")
        else:
            print("404")

    def quit(self):
        self.sock.send(b"E")
        self.sock.close()
        sys.exit("谢谢使用")

    def second_quit(self):
        self.sock.send(b"E")
        self.sock.close()
        sys.exit("谢谢使用")

    def qury(self):
        """查单词"""
        while True:
            word = input("请输入单词:")
            if not word or word == "##":
                break
            request = "Q %s"%word
            self.sock.send(request.encode())
            data = self.sock.recv(1024 * 10).decode()
            if data == "F":
                print("Not Found")
            else:
                print("%s:%s"%(word,data))

    def do_hist(self):
        self.sock.send(b"H")
        data = self.sock.recv(1024*10).decode()
        if data == "F":
            print("您还没有查询记录")
        else:
            rows = data.split("\t")[1].split(';')
            for row in rows:
                print(row)


class ClientView:
    def __init__(self):
        self.handle = Handle()

    def main(self):
        self.first_view()

    def __input_info(self):
        name = input("请输入姓名:")
        password = input("请输入密码,不少于六位:")
        return name,password

    def in_second_view(self):
        c_view.second_view()
        c_view.second_select()

    def first_view(self):
        while True:
            print("""
            ===============显示=============
                按1注册   按2登录    按3退出
            ================================  
            """)
            result = int(input("请输入选择:"))
            if result == 1:
                if self.handle.register(*self.__input_info()):
                   self.in_second_view()
            elif result == 2:
                if self.handle.login(*self.__input_info()):
                    self.in_second_view()
            elif result == 3:
                self.handle.quit()
            else:
                print("请输入正确选择")

    def second_view(self):
        print("""
        ===============显示===========================
            按1查单词   按2查看历史记录  按3注销  
        ==============================================
        """)

    def second_select(self):
        while True:
            result = int(input("请输入选择:"))
            if result == 1:
                self.handle.qury()
            elif result == 2:
               self.handle.do_hist()
            elif result == 3:
                break


if __name__ == '__main__':
    c_view = ClientView()
    c_view.main()